package org.example.consumer.topic;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @description: 消费者
 */
public class TopicConsumer2 {

    public static final String QUEUE_TOPIC_2 = "QUEUE_TOPIC_2";
    //交换机名称
    public static final String EXCHANGE_TOPIC = "EXCHANGE_TOPIC";

    /**
     * 步骤：
     * 1、创建连接
     * 2、创建信道
     * 3、创建队列
     * 4、绑定队列到交换机
     * 5、监听队列
     * 6、处理消息
     */
    public static void main(String[] args) throws Exception {
        //定义连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置连接的mq服务器的IP地址
        factory.setHost("localhost");
        //1、创建连接
        Connection connection = factory.newConnection();
        //2、创建信道
        Channel channel = connection.createChannel();

        //设置消息并发处理数量
        channel.basicQos(1);

        //3、创建队列
        channel.queueDeclare(QUEUE_TOPIC_2, true, false, false, null);

        //4、绑定队列到交换机
        channel.queueBind(QUEUE_TOPIC_2, EXCHANGE_TOPIC, "pethome.#.error");
        channel.queueBind(QUEUE_TOPIC_2, EXCHANGE_TOPIC, "pethome.#.info");

        //5、监听队列
        channel.basicConsume(QUEUE_TOPIC_2, false, new DefaultConsumer(channel){
            //6、处理消息
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("我是消费者Consumer2，收到消息：" + new String(body));
                //手动签收
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }
}